package impl;

import anaydis.sort.SorterType;
import com.sun.org.apache.xml.internal.utils.IntStack;
import org.jetbrains.annotations.NotNull;

import java.util.Comparator;
import java.util.List;

public class QuickSortNonRecursive extends AbstractQuickSorter {

    public QuickSortNonRecursive() {
        super(SorterType.QUICK_NON_RECURSIVE);
    }

    public <T> void sort(@NotNull Comparator<T> comparator,@NotNull List<T> list) {
        sort(comparator, list, 0, list.size() - 1);
    }

    private <T> void sort(Comparator<T> c, List<T> list, int left, int right) {
        IntStack stack = new IntStack();
        stack.push(left);
        stack.push(right);
        while (!stack.empty()) {
            right = stack.pop();
            left = stack.pop();
            if (right <= left) {
                continue;
            }
            int i = partition(c, list, left, right);
            if (i - left > right - i) {
                stack.push(left);
                stack.push(i - 1);
            }
            stack.push(i + 1);
            stack.push(right);
            if (right - i >= i - left) {
                stack.push(left);
                stack.push(i - 1);
            }
        }
    }
}
